package com.sk.weichat.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.CommonRecyclerAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.OnCompleteListener2;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.mvp.presenter.ChatPresenter;
import com.sk.weichat.sortlist.BaseComparator;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.contacts.NewContactsActivity;
import com.sk.weichat.ui.contacts.label.LabelActivity;
import com.sk.weichat.ui.contacts.label.LabelActivity2;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.ui.message.search.SearchActivity;
import com.sk.weichat.ui.message.search.SearchContactActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 好友列表
 * create by swy 2019-07-12
 */
public class TabFriendFragment extends EasyFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private CommonRecyclerAdapter mAdapter;
    private SideBar mSideBar;
    private TextView mTextDialog;
    private List<BaseSortModel<Friend>> mSortFriends;
    private List<BaseSortModel<Friend>> sortedList;
    private String mLoginUserId;
    private int page = 0;
    private int pageSize = 1000;
    private RefreshBroadcastReceiver mRefreshBroadcastReceiver;

    private int lvScrollPosition;


    public TabFriendFragment() {
        mSortFriends = new ArrayList<>();
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_tab_friend;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        mLoginUserId = coreManager.getSelf().getUserId();
        initView();
        loadData();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(mRefreshBroadcastReceiver);
    }

    private void initView() {
        recyclerView = findViewById(R.id.pull_refresh_list);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        initListAdapter();
        refreshLayout = findViewById(R.id.refresh_friend_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 0;
                upDataFriend();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                upDataFriend();
            }
        });
        mSideBar = findViewById(R.id.sidebar);
        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = ListUtil.getPositionForSection(mSortFriends, s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position + 1, 0);
                    showTextDialog(s);
                }
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int visibleItemCount = manager.getChildCount();//屏幕可见item数
                int totalItemCount = manager.getItemCount();//总item数
                int pastVisibleItems = manager.findFirstVisibleItemPosition();//屏幕显示的第一个item的下标index
                if (pastVisibleItems > 1 && visibleItemCount + pastVisibleItems < totalItemCount) {
                    int firstIndex = pastVisibleItems - 1;
                    String firstStr = ListUtil.getFirstStr(mSortFriends, firstIndex);
                    Log.e("lzs", "firstStr:" + firstStr);
                    mSideBar.searchByFirstStr(firstStr);
                    String strLast = ListUtil.getFirstStr(mSortFriends, pastVisibleItems - 2);
                    String strSec = ListUtil.getFirstStr(mSortFriends, pastVisibleItems);
                    if (lvScrollPosition < firstIndex) {
                        if (!firstStr.equals(strLast)) {
                            showTextDialog(firstStr);
                        }
                    } else if (lvScrollPosition > firstIndex) {
                        if (!firstStr.equals(strSec)) {
                            showTextDialog(firstStr);
                        }
                    }
                }
                lvScrollPosition = pastVisibleItems - 1;
            }
        });
        mRefreshBroadcastReceiver = new RefreshBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.NAME_CHANGE);
        mActivity.registerReceiver(mRefreshBroadcastReceiver, intentFilter);
    }

    private class RefreshBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(com.sk.weichat.broadcast.OtherBroadcast.NAME_CHANGE)) {
                upDataFriend();
            }
        }
    }

    //初始化适配器及事件
    private void initListAdapter() {
        mAdapter = new CommonRecyclerAdapter(R.layout.row_sort_friend, mSortFriends) {
            @Override
            public void convert(BaseViewHolder holder, int position) {
                position = position - 1;//添加了一个头部
                TextView categoryTitleTv = holder.getView(R.id.catagory_title);
                ImageView avatar_img = holder.getView(R.id.avatar_img);
                TextView nick_name_tv = holder.getView(R.id.nick_name_tv);
                // 根据position获取分类的首字母的Char ascii值
                int section = ListUtil.getSectionForPosition(mSortFriends, position);
                // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
                if (position == ListUtil.getPositionForSection(mSortFriends, section)) {
                    categoryTitleTv.setVisibility(View.VISIBLE);
                    categoryTitleTv.setText(mSortFriends.get(position).getFirstLetter());
                } else {
                    categoryTitleTv.setVisibility(View.GONE);
                }
                Friend friend = mSortFriends.get(position).getBean();
                if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    avatar_img.setImageResource(R.mipmap.ic_service);
                } else {
                    AvatarHelper.getInstance().displayAvatar(friend.getUserId(), avatar_img, true);
                }
                // 昵称
                nick_name_tv.setText(!TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : friend.getNickName());
                int finalPosition = position;
                avatar_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Friend friend = mSortFriends.get(finalPosition).getBean();
                        Intent intent = new Intent(mActivity, PersonalCenterActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                        mActivity.startActivity(intent);
                    }
                });
            }
        };
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = mSortFriends.get(position).getBean();
                Intent intent = new Intent(requireActivity(), ChatActivity.class);
                intent.putExtra(ChatActivity.FRIEND, friend);
                intent.putExtra(Constants.NEW_MSG_NUMBER, friend.getUnReadNum());
                requireActivity().startActivity(intent);
            }
        });
        View headView = LayoutInflater.from(mActivity).inflate(R.layout.tab_fragment_head, recyclerView, false);
        mAdapter.addHeaderView(headView);

        headView.findViewById(R.id.layout_tab_friend_search).setOnClickListener(this);
        headView.findViewById(R.id.layout_tab_label).setOnClickListener(this);
        headView.findViewById(R.id.layout_tab_contact).setOnClickListener(this);

        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setHasStableIds(true);
        recyclerView.setAdapter(mAdapter);
    }

    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.layout_tab_friend_search:
                //搜索
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                getActivity().startActivity(intent);
                break;

            case R.id.layout_tab_label:
                //标签
                //LabelActivity.start(requireContext());
                Intent intent2 = new Intent(getActivity(), LabelActivity2.class);
                startActivity(intent2);
                break;
            case R.id.layout_tab_contact:
                //联系人
                Intent intentGroup = new Intent(getActivity(), NewContactsActivity.class);
                getActivity().startActivity(intentGroup);
                break;
        }

    }

    public void refreshData() {
        page = 0;
        upDataFriend();
    }


    private void loadData() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(getActivity());
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            final List<Friend> friends = FriendDao.getInstance().getAllFriends(mLoginUserId);
            Map<String, Integer> existMap = new HashMap<>();
            if (sortedList != null) {
                sortedList.clear();
            }
            sortedList = SortHelper.toSortedModelList(friends, existMap, Friend::getShowName);
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                mSideBar.setExistMap(existMap);
                if (!ListUtil.isListEmpty(sortedList)) {
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                mSortFriends.removeAll(mSortFriends);
                mSortFriends.addAll(sortedList);
                mAdapter.notifyDataSetChanged();

            });
        });
    }

    /**
     * 从服务端获取好友列表，更新数据库
     */
    private void upDataFriend() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("pageIndex", page + "");
        params.put("pageSize", pageSize + "");
        params.put("status", "2");//好友关系状态：1、关注；2，好友；5，粉丝；如果不传三种关系都查

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<User>(User.class) {
                    @Override
                    public void onResponse(ArrayResult<User> result) {
                        if (page == 0) {
                            refreshLayout.finishRefresh();
                        } else {
                            refreshLayout.finishLoadMore();
                        }

                        if (result.getResultCode() == 1) {
                            AsyncUtils.doAsync(TabFriendFragment.this, e -> {
                                Reporter.post("保存好友失败，", e);
                                AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                                    ToastUtil.showToast(ctx, R.string.data_exception);
                                });
                            }, c -> {

                                FriendDao.getInstance().addUserList(coreManager.getSelf().getUserId(), result.getData(),
                                        new OnCompleteListener2() {

                                            @Override
                                            public void onLoading(int progressRate, int sum) {

                                            }

                                            @Override
                                            public void onCompleted() {
                                                c.uiThread(r -> {
                                                    r.loadData();
                                                    ((TabFriendActivity) getActivity()).downloadUserInfo();
                                                });
                                            }
                                        });
                                if (result.getData().size() == pageSize) {
                                    refreshLayout.setEnableLoadMore(true);
                                    refreshLayout.setEnableAutoLoadMore(true);
                                } else {
                                    refreshLayout.setEnableLoadMore(false);
                                }

                            });
                        } else {
                            ToastUtil.showToast(mActivity, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        refreshLayout.finishRefresh();
                        ToastUtil.showErrorNet(getActivity());
                    }
                });
    }

}
